/**
 * 数据验证和安全访问工具
 */
class DataValidator {
  
  /**
   * 安全获取对象属性（支持深度路径）
   * @param {Object} obj 目标对象
   * @param {String} path 属性路径，如 'store.phone' 或 'user.profile.name'
   * @param {*} defaultValue 默认值
   * @returns {*} 属性值或默认值
   */
  static safeGet(obj, path, defaultValue = null) {
    if (!obj || typeof obj !== 'object') {
      return defaultValue
    }
    
    try {
      const keys = path.split('.')
      let result = obj
      
      for (const key of keys) {
        if (result === null || result === undefined || typeof result !== 'object') {
          return defaultValue
        }
        result = result[key]
      }
      
      return result !== undefined ? result : defaultValue
    } catch (error) {
      console.warn('SafeGet error:', error.message, { obj, path })
      return defaultValue
    }
  }

  /**
   * 验证订单对象完整性
   * @param {Object} order 订单对象
   * @returns {Object} 验证结果
   */
  static validateOrder(order) {
    const errors = []
    const warnings = []
    
    // 基础字段验证
    if (!order) {
      errors.push('订单对象为空')
      return { isValid: false, errors, warnings }
    }
    
    if (!order.id) {
      errors.push('缺少订单ID')
    }
    
    if (!order.orderNo) {
      warnings.push('缺少订单号')
    }
    
    if (!order.status) {
      errors.push('缺少订单状态')
    }
    
    if (!order.totalAmount) {
      errors.push('缺少订单金额')
    }
    
    // 店铺信息验证
    if (!order.store) {
      errors.push('缺少店铺信息')
    } else {
      if (!order.store.id) {
        warnings.push('缺少店铺ID')
      }
      if (!order.store.name) {
        warnings.push('缺少店铺名称')
      }
      if (!order.store.phone) {
        warnings.push('缺少店铺电话')
      }
    }
    
    // 商品列表验证
    if (!order.items || !Array.isArray(order.items) || order.items.length === 0) {
      errors.push('缺少商品列表')
    } else {
      order.items.forEach((item, index) => {
        if (!item.productId) {
          warnings.push(`商品${index + 1}缺少产品ID`)
        }
        if (!item.name) {
          warnings.push(`商品${index + 1}缺少名称`)
        }
        if (!item.price) {
          warnings.push(`商品${index + 1}缺少价格`)
        }
        if (!item.quantity) {
          warnings.push(`商品${index + 1}缺少数量`)
        }
      })
    }
    
    return {
      isValid: errors.length === 0,
      errors,
      warnings
    }
  }

  /**
   * 补全订单对象缺失的字段
   * @param {Object} order 订单对象
   * @returns {Object} 补全后的订单对象
   */
  static completeOrder(order) {
    if (!order) {
      return this.createDefaultOrder()
    }
    
    const completed = {
      id: order.id || Date.now(),
      orderNo: order.orderNo || 'ORD' + Date.now(),
      status: order.status || 'PENDING',
      type: order.type || 'DELIVERY',
      totalAmount: order.totalAmount || '0.00',
      productAmount: order.productAmount || '0.00',
      deliveryFee: order.deliveryFee || '0.00',
      packagingFee: order.packagingFee || '0.00',
      discountAmount: order.discountAmount || '0.00',
      createdAt: order.createdAt || new Date(),
      ...order
    }
    
    // 补全店铺信息
    if (!completed.store) {
      completed.store = this.createDefaultStore()
    } else {
      completed.store = {
        id: completed.store.id || 1,
        name: completed.store.name || '未知商家',
        avatarUrl: completed.store.avatarUrl || '/images/default-store.png',
        address: completed.store.address || '地址未知',
        phone: completed.store.phone || '暂无电话',
        businessHours: completed.store.businessHours || '营业时间未知',
        rating: completed.store.rating || 0,
        ...completed.store
      }
    }
    
    // 补全商品列表
    if (!completed.items || !Array.isArray(completed.items)) {
      completed.items = []
    } else {
      completed.items = completed.items.map((item, index) => ({
        productId: item.productId || index + 1,
        name: item.name || '未知商品',
        image: item.image || item.imageUrl || '/images/default-product.png',
        price: item.price || 0,
        quantity: item.quantity || 1,
        specifications: item.specifications || '标准',
        ...item
      }))
    }
    
    // 补全地址信息（配送订单）
    if (completed.type === 'DELIVERY' && !completed.deliveryAddress) {
      completed.deliveryAddress = '配送地址未知'
      completed.receiverName = completed.receiverName || '收货人'
      completed.receiverPhone = completed.receiverPhone || '联系电话'
    }
    
    return completed
  }

  /**
   * 创建默认订单对象
   * @returns {Object} 默认订单
   */
  static createDefaultOrder() {
    return {
      id: Date.now(),
      orderNo: 'ORD' + Date.now(),
      status: 'PENDING',
      type: 'DELIVERY',
      totalAmount: '0.00',
      productAmount: '0.00',
      deliveryFee: '0.00',
      packagingFee: '0.00',
      discountAmount: '0.00',
      createdAt: new Date(),
      store: this.createDefaultStore(),
      items: [],
      deliveryAddress: '配送地址未知',
      receiverName: '收货人',
      receiverPhone: '联系电话'
    }
  }

  /**
   * 创建默认店铺对象
   * @returns {Object} 默认店铺
   */
  static createDefaultStore() {
    return {
      id: 1,
      name: '未知商家',
      avatarUrl: '/images/default-store.png',
      address: '地址未知',
      phone: '暂无电话',
      businessHours: '营业时间未知',
      rating: 0
    }
  }

  /**
   * 验证并修复用户对象
   * @param {Object} user 用户对象
   * @returns {Object} 修复后的用户对象
   */
  static validateUser(user) {
    if (!user || typeof user !== 'object') {
      return {
        id: null,
        nickname: '游客',
        avatarUrl: '/images/default-avatar.png',
        phone: '',
        isLogin: false
      }
    }
    
    return {
      id: user.id || null,
      nickname: user.nickname || user.name || '游客',
      avatarUrl: user.avatarUrl || user.avatar || '/images/default-avatar.png',
      phone: user.phone || '',
      isLogin: !!user.id,
      ...user
    }
  }

  /**
   * 格式化价格显示
   * @param {*} price 价格值
   * @returns {String} 格式化后的价格字符串
   */
  static formatPrice(price) {
    const num = parseFloat(price)
    if (isNaN(num)) {
      return '0.00'
    }
    return num.toFixed(2)
  }

  /**
   * 格式化时间显示
   * @param {*} time 时间值
   * @returns {String} 格式化后的时间字符串
   */
  static formatTime(time) {
    if (!time) return '时间未知'
    
    try {
      const date = new Date(time)
      if (isNaN(date.getTime())) {
        return '时间格式错误'
      }
      
      const now = new Date()
      const diff = now.getTime() - date.getTime()
      
      if (diff < 0) {
        // 未来时间
        const minutes = Math.ceil(Math.abs(diff) / (60 * 1000))
        return `${minutes}分钟后`
      } else if (diff < 60 * 1000) {
        return '刚刚'
      } else if (diff < 60 * 60 * 1000) {
        return `${Math.floor(diff / (60 * 1000))}分钟前`
      } else if (diff < 24 * 60 * 60 * 1000) {
        return `${Math.floor(diff / (60 * 60 * 1000))}小时前`
      } else {
        return `${date.getMonth() + 1}-${date.getDate()} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
      }
    } catch (error) {
      console.warn('FormatTime error:', error.message)
      return '时间解析错误'
    }
  }

  /**
   * 批量验证对象数组
   * @param {Array} items 对象数组
   * @param {Function} validator 验证函数
   * @returns {Object} 验证结果
   */
  static validateArray(items, validator) {
    if (!Array.isArray(items)) {
      return {
        isValid: false,
        validItems: [],
        invalidItems: [{ error: '输入不是数组' }]
      }
    }
    
    const validItems = []
    const invalidItems = []
    
    items.forEach((item, index) => {
      try {
        const validation = validator(item, index)
        if (validation.isValid) {
          validItems.push(validation.item || item)
        } else {
          invalidItems.push({
            index,
            item,
            errors: validation.errors || ['验证失败']
          })
        }
      } catch (error) {
        invalidItems.push({
          index,
          item,
          errors: [error.message]
        })
      }
    })
    
    return {
      isValid: invalidItems.length === 0,
      validItems,
      invalidItems,
      total: items.length,
      validCount: validItems.length,
      invalidCount: invalidItems.length
    }
  }

  /**
   * 检查必需字段
   * @param {Object} obj 目标对象
   * @param {Array} requiredFields 必需字段列表
   * @returns {Object} 检查结果
   */
  static checkRequiredFields(obj, requiredFields) {
    const missing = []
    const present = []
    
    requiredFields.forEach(field => {
      const value = this.safeGet(obj, field)
      if (value === null || value === undefined || value === '') {
        missing.push(field)
      } else {
        present.push(field)
      }
    })
    
    return {
      isComplete: missing.length === 0,
      missing,
      present,
      completeness: (present.length / requiredFields.length * 100).toFixed(1) + '%'
    }
  }
}

module.exports = {
  DataValidator,
  safeGet: DataValidator.safeGet.bind(DataValidator),
  validateOrder: DataValidator.validateOrder.bind(DataValidator),
  completeOrder: DataValidator.completeOrder.bind(DataValidator),
  formatPrice: DataValidator.formatPrice.bind(DataValidator),
  formatTime: DataValidator.formatTime.bind(DataValidator)
} 